﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;

namespace QueryTest2
{
    public class TestHelper
    {
        internal static List<methodDetail> GetMethods(List<methodDetail> customMethods = null)
        {
            var type1 = typeof(QueryTest.test.config);
            var asb = Assembly.GetAssembly(type1);
            var types = asb.GetTypes().Where(b => b.Namespace == type1.Namespace && b.IsPublic).ToArray();

            var allMethods = new List<methodDetail>();
            foreach (var currentType in types)
            {
                var allMethods2 = currentType.GetMethods(BindingFlags.Static | BindingFlags.Public).Where(b => b.Name != "Main").Select(b => new methodDetail
                {
                    func = (d) => b.Invoke(null, null),
                    text = b.Name,
                    tag = currentType.Name,
                    typeName = currentType.Name,
                    fullName = $"{currentType.FullName}.{b.Name}"
                }).ToList();
                allMethods.AddRange(allMethods2);
            }
            if (customMethods != null)
            {
                allMethods.AddRange(customMethods);
            }
            //var allMethods_ = allMethods.Where(x => x.typeName != "config");
            allMethods.Add(new methodDetail
            {
                text = "invokeAll",
                tag = "invokeAll",
                typeName = "invokeAll",
                fullName = "invokeAll"
            });
            var path = @"..\QueryTest\test";
            var sourceCodes = QueryTest.CodeHelper.LoadFiles(path);
            foreach (var m in allMethods)
            {
                var a = sourceCodes.TryGetValue(m.fullName, out var s);
                m.sourceCode = s?.sourceCode?.ToString();
            }
            return allMethods;
        }
        internal static async Task<List<string>> InvokeAllMethod(List<methodDetail> methods)
        {
            var lines = new List<string>();
            foreach (var method in methods)
            {
                if (method.typeName == "config")
                {
                    continue;
                }
                var lines2 = await InvokeMethod(method);
                lines.AddRange(lines2);
            }
            return lines;
        }
        internal static async Task<List<string>> InvokeMethod(methodDetail method)
        {
            var oldWriter = Console.Out;
            var writer = new TextWriter2(oldWriter);
            Console.SetOut(writer);
            var invokeResult = "";
            var sw = new System.Diagnostics.Stopwatch();
            sw.Start();
            try
            {
                var result = method.func(method);
                if (result is Task)
                {
                    var task = (Task)result;
                    await task;
                }
                if (result != null)
                {
                    Console.WriteLine($"invoke Result: {System.Text.Json.JsonSerializer.Serialize(result)}");
                }
                invokeResult = $"{method.text} invoke completed";
                method.invokeResult = true;
            }
            catch (Exception ero)
            {
                invokeResult = ero.InnerException?.ToString();
                method.invokeResult = false;
            }
            sw.Stop();
            var el = sw.ElapsedMilliseconds;
            method.invokeTime = DateTime.Now;
            method.invokeEl = el;
            var allLine = writer.texts;
            writer.Dispose();
            Console.SetOut(oldWriter);
            allLine.Add(invokeResult);
            method.invokeLog = allLine;
            return allLine;
        }
    }
    public class methodDetail
    {
        public string fullName;
        public string sourceCode;
        public string text;
        public Func<methodDetail, object> func;
        public object data;
        public bool? invokeResult;
        public DateTime? invokeTime;
        public List<string> invokeLog = new List<string>();
        public long? invokeEl;
        public string tag;
        internal string typeName;
    }
    class TextWriter2 : System.IO.TextWriter
    {
        public List<string> texts = new List<string>();
        TextWriter _old;
        public TextWriter2(TextWriter old)
        {
            _old = old;
        }
        public override void Write(char value)
        {
            _old.Write(value);
            if (string.IsNullOrWhiteSpace(value.ToString()))
            {
                return;
            }
            //base.Write(value);//still output to Console
            texts.Add(value.ToString());
        }
        public override void Write(string value)
        {
            _old.Write(value);
            if (string.IsNullOrWhiteSpace(value.ToString()))
            {
                return;
            }

            if (value == "\r\n")
            {
                return;
            }
            texts.Add(value);
        }

        public override System.Text.Encoding Encoding
        {
            get { return System.Text.Encoding.UTF8; }
        }
    }
}
